import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/login/login.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  /* home */
  {
    path: '/',
    name: 'Home',
    meta: {
      isLogin: true
    },
    component: Home
  },
  {
    path: '/home',
    redirect: '/'
  },
  /** todoList */
  {
    path: '/todoList',
    redirect: '/todoList/db'
  },
  {
    path: '/todoList/:title',
    name: 'todoList',
    meta: {
      isLogin: true
    },
    component: () => import('@/views/todoList/todoList.vue')
  },
  /* newsList */
  {
    path: '/newsList',
    redirect: '/newsList/zxxw'
  },
  {
    path: '/newsList/:title',
    name: 'newsList',
    meta: {
      isLogin: true
    },
    component: () => import('@/views/newsList/newsList.vue')
  },
  /* appStore */
  {
    path: '/appStore',
    redirect: '/appStore/cyyy'
  },
  {
    path: '/appStore/:title',
    name: 'appStore',
    meta: {
      isLogin: true
    },
    component: () => import('@/views/appStore/appStore.vue')
  },
  /* contactBooks */
  {
    path: '/contactBooks',
    name: 'contactBooks',
    meta: {
      isLogin: true
    },
    component: () => import('@/views/contactBooks/contactBooks.vue')
  },
  /** commingSoon */
  {
    path: '/commingSoon',
    name: 'commingSoon',
    meta: {
      isLogin: true
    },
    component: () => import('@/views/commingSoon/commingSoon.vue')
  },
  /** details */
  {
    path: '/details/:id',
    name: 'details',
    meta: {
      isLogin: true
    },
    component: () => import('@/views/details/details.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // roleType标志
  if (to.matched[0].meta.isLogin) {
    /** 为了开发方便将 router.app.$options.store.state.userinfo 改成 localStorage.getItem('userinfo') 否则vuex一刷新就没有，vuex持久化和直接存没有什么区别 */
    if (localStorage.getItem('isLogin') && localStorage.getItem('userinfo')) {
      // localStorage.getItem('userinfo')
      // console.log(router.app.$options.store.state.userinfo.roleType * 1, '++router')
      // decodeURI(localStorage.getItem('userinfo'))
      if (to.name === 'todoList') {
        if (JSON.parse(decodeURI(localStorage.getItem('userinfo'))).roleType * 1 > 1) {
          next()
        } else {
          next(from.path)
          alert('你没有权限哦！')
        }
      } else {
        next()
      }
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
